var twbUpdateOrderPageVm  = new Vue({
    el: '#twbUpdateOrderPage',
    data: function(){
      return  {
            //打开修改订单页面
            updateOrderPageVisible: false,
            //防止重复添加订单:
            orderVisible:true,
            //添加订单包装类
            erpOrderItemDto:{erpOrder:{},erpOrderItemList:[]},
            title:'修改订单',
            //订单对象
            erpOrder:{memberName:'',shipName:'',shipMobile:'',orderCreatetime:'',acceptOrderUser:'',shipArea:'',shipAddr:''},
            //商品明细
            erpOrderItemData:[],
            //商品明细勾选项，用于删除
            selectedItemData:[],
            //查询的产品集合
            productData:[],
            //客户信息
            storeMemberData:[],
              //加载客户
              loading:false,
            //会员折扣
            discountRate:0,
            /* 省市区回显 */
            areaCascader: [],
            itemForm:[],
            //添加订单校验规则
            addRules:{
            memberName:{ required: true, //是否必填
                message: '请选择客户', //规则
                trigger: 'change'  //何事件触发
            },
            shipName:[
                { required: true,message:'请输入联系人',trigger: 'blur'}
            ],
                orderCreatetime:[
                { required: true,message:'请选择接单时间',trigger: 'blur'}
            ],
                shipMobile:[{ pattern: /^1[34578]\d{9}$/, message:'请输入正确的手机号', trigger: 'blur'},
            ]
        },
            itemRules:{
              name:[
                  {required: true, message: '商品名称不能为空', trigger: 'change'},
              ],
              nums:[
                  {required: true,pattern:/^([1-9][0-9]*(\.\d{1,2})?)|(0\.\d{1,2})$/, message: '请输入正确数量', trigger: 'blur'},
              ],
              copy:[
                  {required: true,pattern:/^[1-9]\d*$/, message: '请输入正确份数,必须为正整数', trigger: 'blur'},
              ],
              amount:[
                  {required: true,pattern:/^([1-9][0-9]*(\.\d{1,2})?)|(0\.\d{1,2})$/, message: '请输入正确总价', trigger: 'blur'},
              ],
              price:[{required: true,pattern:/^([1-9][0-9]*(\.\d{1,2})?)|(0\.\d{1,2})$/, message: '请输入正确单价', trigger: 'blur'},]
          },
            //支付方式
            payTypeData:[],
                //表单对齐方式
                labelPosition: 'right',
            //地区用于选择收货地区
            area:[],
            salesManList:[],
            acceptOrderUserData:[],
            //是否可挂账
            credit:false,
            memberLoading: false,
        }
    },
    methods: {
        /* 初始化 */
        loadData: function (data) {
            if(isBlank(data.orderNo)){
                alert("请勾选一行再进行操作!");
                return;
            }
            var orderNo=data.orderNo;
            this.getInfo(orderNo);
        },
        getInfo:function(orderNo){
            var self=this;
            self.erpOrder={memberName:'',shipName:'',shipMobile:'',orderCreatetime:'',acceptOrderUser:'',shipArea:'',shipAddr:'',shipAreaId:'',deposit:false,payed:0};
            var url="twbOrder/erporder/orderInfo/"+orderNo;
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                success: function(r){
                    if(r.code === 0){
                        self.erpOrderItemData=r.erpOrderItemData;
                        self.erpOrder=r.erpOrder;
                        self.acceptOrderUserData=r.acceptOrderUserData;
                        self.erpOrder.acceptOrderUser=r.currentUser;
                        self.itemForm.erpOrderItemData=r.erpOrderItemData;
                        self.area=JSON.parse(r.area);
                        self.updateOrderPageVisible=true;
                        //处理省市区回显
                        var regionPath =  self.erpOrder.shipArea;
                        if(!isBlank(regionPath)){
                            var  arr=regionPath.split(/\s+/);
                            if(arr.length==3){
                                self.areaCascader= self.cascaderRet(arr,self.area);
                            }
                        }
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },

        /*修改订单*/
        update:function(){
            var self=this;
            self.erpOrderItemDto.erpOrder=self.erpOrder;
            if(self.erpOrderItemData.length==0){
                alert("商品明细不能为空");
                return;
            }
            self.erpOrderItemDto.erpOrderItemList=self.itemForm.erpOrderItemData;
            var url="twbOrder/erporder/update"
            this.$refs["addForm"].validate(function (valid){
                if(valid){
                    self.$refs["itemForm"].validate(function (valid) {
                        if(valid){
                            self.orderVisible=false;
                            $.ajax({
                                type: "POST",
                                url: baseURL + url,
                                contentType: "application/json",
                                data:JSON.stringify(self.erpOrderItemDto),
                                success: function(r){
                                    if(r.code === 0){
                                        alert('操作成功', function(index){
                                            self.reload();
                                        });
                                    }else{
                                        alert(r.msg);
                                    }
                                }
                            });
                        }
                    })
                }
            });
        },
        /* 更改省市区 */
        handleAreaChange:function(val){
            var values = val.join(',').split(',');
            var areaId = values[val.length - 1];
            var lableVal =this.getCascaderObj(val, this.area);
            this.erpOrder.shipAreaId = areaId;
            var area = lableVal.join(',').replace(new RegExp(',', 'g'), ' ');
            this.erpOrder.shipArea = area;
        },
        getCascaderObj(val, opt) {
            return val.map(function (value, index, array) {
                for (var itm in opt) {
                    if (opt[itm].value == value) {
                        var label = opt[itm].label;
                        opt = opt[itm].children;
                        return label;
                    }
                }
                return null;
            });
        },
        //远程搜索客户
        searchMember:function(query){
            if(query.type=='focus'){
                query='';
            }
            debugger
            var self=this;
            var url="twbOrder/erporder/searchMember"
            var param={'name':query.trim()};
            setTimeout(function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json;charset=UTF-8",
                    data:JSON.stringify(param),
                    success: function(r){
                        if(r.code === 0){
                            self.storeMemberData=r.storeMemberData;
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            },250)
        },
        selectStoreMember:function(val){
            if(val!=null&&val!=undefined){
                for (var i=0;i<this.storeMemberData.length;i++){
                    var item=this.storeMemberData[i];
                    if(item.storeMemberId==val){
                        this.erpOrder.storeMemberId=item.storeMemberId;
                        this.erpOrder.memberName=item.name;
                        this.erpOrder.shipName=item.nickname;
                        this.erpOrder.memberId=item.memberId;
                        this.erpOrder.shipMobile=item.mobile;
                        this.erpOrder.shipAddr=item.addr;
                        this.credit=item.hangsAccountCustomer;
                        this.erpOrder.onCredit=item.hangsAccountCustomer;
                        if(val.discountRate){
                            this.discountRate=item.discountRate;
                        };
                    }
                }
            }
        },
        //改变产品明细数量
        handleNums:function(value,row){
            var  reg = /[^\d\.]/g;
            if (value && new RegExp(reg).test(value)) {//非数字
                this.$message({
                    message: '请输入正确的数字',
                    type: 'warning'
                })
                row.nums=1;
                return;
            }
            row.amount=value*row.price*row.copy;
            if(isNaN(row.amount)){
                row.amount=0;
            }
        },
        //改变价格
        handlePrice:function(value,row){
            var  reg = /[^\d\.]/g;
            if (value && new RegExp(reg).test(value)) {//非数字
                this.$message({
                    message: '请输入正确的数字',
                    type: 'warning'
                })
                return;
            }
            row.amount=row.price*row.nums*row.copy;
            if(isNaN(row.amount)){
                row.amount=0;
            }
        },
        //处理单位
        handleUnit:function(value,row){
            var  reg = /[@#\$%\^&\*]+/g;
            if (value && new RegExp(reg).test(value)) {
                this.$message({
                    message: '请输入正确单位，不允许包含特殊字符',
                    type: 'warning'
                })
                row.unit='';
                return;
            }
        },
        //改变总价
        handleAmount:function(value,row){
            var  reg = /[^\d\.]/g;
            //校验数量
            if (row.nums && new RegExp(reg).test(row.nums)||row.nums==0) {//非数字
                this.$message({
                    message: '请确认数量是否正确',
                    type: 'warning'
                })
                row.amount=''
                return;
            }
            //校验数量
            if (row.copy && new RegExp(reg).test(row.copy)||row.copy==0) {//非数字
                this.$message({
                    message: '请确认份数是否正确',
                    type: 'warning'
                })
                row.amount='';
                return;
            }
            var  reg = /[^\d\.]/g;
            if (value && new RegExp(reg).test(value)) {//非数字
                this.$message({
                    message: '请输入正确的数字',
                    type: 'warning'
                })
                return;
            }
            row.price=((value/row.nums)/row.copy).toFixed(3);
        },
        //新增明细
        addItem:function(){
            var item={name:'',addon:'',unit:'',nums:1,copy:1,price:'',amount:''};
            this.erpOrderItemData.push(item);
        },
        //删除明细
        delItem:function(index,rows){
            rows.splice(index, 1);
        },
        querySearchProduct:function(queryString, cb){
        var self=this;
          var item={"name":queryString}
            setTimeout(function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "twbOrder/erporder/querySearchProduct",
                    contentType: "application/json;charset=UTF-8",
                    data:JSON.stringify(item),
                    success: function(r){
                        if(r.code == 0){
                            self.productData=r.productData;
                            cb( self.productData);
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            } ,400);
        },

        //选择产品名称
        handleSelectProduct:function(item,row){
            row.name=item.name;
            row.addon=item.productInfo;
            row.price=item.totalPrice;
            row.goodsId=item.goodsId;
            row.productId=item.productId;
            row.unit=item.unit;
            row.nums=1;
            row.copy=1;
            row.amount=item.totalPrice*row.nums;
            row.pmtGoods=0;
        },

        reload:function(){
            var self=this;
            self.updateOrderPageVisible=false;
            twbOrderVm.reload();
        },

        //处理省市区回显,
        cascaderRet:function(arr,area){
            var province='';
            var city='';
            var are='';
            var cityArray=[];
            var areaArray=[];
            var resArray=[];
            for (var i=0;i<area.length;i++){
                if(arr[0]==area[i].label){
                    province=area[i].value;
                    cityArray=area[i].children;
                    break;
                }
            }
            for (var i=0;i<cityArray.length;i++) {
                if(arr[1]==cityArray[i].label){
                    city=cityArray[i].value;
                    areaArray=cityArray[i].children;
                    break;
                }
            }
            for (var i=0;i<areaArray.length;i++) {
                if(arr[2]==areaArray[i].label){
                    are=areaArray[i].value;
                    break;
                }
            }
            resArray.push(province);
            resArray.push(city);
            resArray.push(are);
            return resArray;
        },
    }
})